<?php


namespace App\Services;

use App\Dao\UsersDao;
use App\Exceptions\SysExceptions;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * Class OpenLoginServices
 * @package App\Services
 * author:fhc
 * desc:开放登录
 * created_at: 2020/11/25 - 10:48 下午
 */
class WechatServices
{
    //app的appid
    private static $appId = 'wxaaf42877a81de40c';

    private static $appSercert = 'f78ccbd1365a7946aa539110b646559b';

    //公众号appid
    private static $app_id_publick = 'wxe434bddb79128e13';
    //公众号appsercert
    private static $app_sercert_publick = '8d5329629cb4bed5fca53d4666f1bf07';

    private static $tea_pub_url = 'http://m2lzv0vn.dongtaiyuming.net';




    /**
     * author:fhc
     * desc:微信公众号登陆
     * created_at: 2021/3/24 - 3:37 下午
     * @param $code
     * @return mixed
     */
    public static function wx_publick_login($code){
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::$app_id_publick.'&secret='.self::$app_sercert_publick.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(self::curl_get($token_url),true);
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token['access_token']."&openid=".$token["openid"]."&lang=zh_CN";
        $userInfo = self::curl_get($url);
        return json_decode($userInfo,true);
    }



    /**
     * author:fhc
     * desc:获取
     * created_at: 2021/6/3 3:34 下午
     * @param string $url
     * @return array
     * @throws InvalidArgumentException
     */
    public static function getSinge($url = ''): array
    {
        $ticket = self::getJsSdk();
        $timestamp = time();
        $nonceStr = self::createNonceStr();
        $str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $sha_str = sha1($str);
        return [
            'timestamp'=>$timestamp,
            'signature'=>$sha_str,
            'nonceStr'=>$nonceStr,
            'appid'=>self::$app_id_publick
        ];
    }

    /**
     * @param int $length
     * @return string
     * author:fhc
     * desc:字符串随机
     * created_at: 2021/6/3 3:35 下午
     */
    static function createNonceStr($length = 16): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    /**
     * author:fhc
     * desc:获取jssdk
     * created_at: 2021/6/3 3:08 下午
     * @throws InvalidArgumentException
     */
    public static function getJsSdk(){
        $key = 'js_ticket_wechat';
        if(Cache::hasCache($key)){
            return Cache::getCacheValue($key);
        }
        $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".self::getAccessToken()."&type=jsapi";
        $ticket_res = self::curl_get($ticket_url);
        $ticket_res = json_decode($ticket_res, true);
        $ticket = $ticket_res['ticket'];
        Cache::setCache($key,$ticket,3600);
        return $ticket;
    }

    /**
     * author:fhc
     * desc:获取access_token
     * created_at: 2021/6/3 3:23 下午
     * @throws InvalidArgumentException
     */
    public static function getAccessToken(){
        $key = 'access_token_wechat';
        if(Cache::hasCache($key)){
            return  Cache::getCacheValue($key);
        }
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$app_id_publick."&secret=".self::$app_sercert_publick;
        $token_res = self::curl_get($token_url);
        $token_res = json_decode($token_res, true);
        $token = $token_res['access_token'];

        Cache::setCache($key,$token,6200);
        return $token;
    }




    //curl_post
    public static function curl_post($url , $data=array()){

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        // POST数据

        curl_setopt($ch, CURLOPT_POST, 1);

        // 把post的变量加上

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);

        curl_close($ch);

        return $output;

    }

    static function curl_get($url){

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        curl_close($curl);

        return $data;
    }
}
